<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends BackendController
{
	function __construct()
	{
		parent::__construct();
		$this->group = array(
			1=>lang('admin'),
			2=>lang('member'),
		);
		$this->lang->load('user');
		$this->load->model('user_model');
	}
	public function index($page=0)
	{
		$page = intval(str_replace('page-', '', $page));
		$limit = $this->config->item('per_page');
		if($page < 1) $page = 1;
		$limit_start = ($page - 1) * $limit;

		$keyword = $this->filter->get('keyword');
		if($keyword)
		{
			$where_like = $this->db->escape('%'.$this->db->escape_like_str($keyword).'%');
			$this->user_model->list_where = 'fullname LIKE '.$where_like;
		}

		$this->user_model->list_ordering = $this->filter->get('ordering', 'id');
		$this->user_model->list_direction = $this->filter->get('direction', 'DESC');
		$items = $this->user_model->getList($limit, $limit_start);
		foreach($items as $idx=>$item)
		{
			$items[$idx]->group = $this->group[$item->group_id];
		}
		$total = $this->user_model->getTotal();

		$this->load->library('pagination');
		$link = site_url('admin/user/index');
		$this->pagination->initialize( array(
			'base_url' => $link,
			'first_url' => $link,
			'total_rows' => $total,
			'per_page' => $limit,
			'prefix' => 'page-',
			'cur_page' => $page,
		) );
		$data = array(
			'link'=>$link,
			'items'=>$items,
			'filter'=>$this->filter->getdata(),
			'ordering'=>$this->user_model->list_ordering,
			'direction'=>$this->user_model->list_direction,
		);

		$this->filter->store();
		if($this->input->get('ajax'))
		{
			//$this->output->set_template('ajax');
			$temp = 'items_list';
		}
		else
		{
			$this->output->set_template('backend');
			$this->output->set_title(lang('user_manager'));
			$temp = 'items';
		}
		$this->load->view('backend/user/'.$temp, $data);
	}
	public function form($id=0)
	{
		if($this->user->id!=1 && $id==1)
		{
			$this->messages->add(lang('error_forbidden'), 'e');
			redirect($this->return->get('last'));
		}

		$id = intval($id);
		$this->load->library('form_validation');

		if($id)
		{
			$item = $this->user_model->getItem($id);
			if(!$item)
			{
				$this->messages->add(lang('not_found'), 'e');
				redirect(site_url('admin/user/index'));
			}
			$this->output->set_title(lang('user_edit'));
			$this->form_validation->set_rules('password', 'lang:password', 'trim|min_length[6]|max_length[64]|xss_clean|matches[repassword]');
		}
		else
		{
			$item = $this->user_model->blankItem();
			$item->published = 1;
			$this->output->set_title(lang('user_add'));
			$this->form_validation->set_rules('password', 'lang:password', 'trim|required|min_length[6]|max_length[64]|xss_clean|matches[repassword]');
		}

		$this->form_validation->set_rules('fullname', 'lang:fullname', 'trim|required|min_length[3]|max_length[64]|xss_clean');
		$this->form_validation->set_rules('username', 'lang:username', 'required|min_length[3]|max_length[32]|xss_clean|callback_username_check');
		$this->form_validation->set_rules('repassword', 'lang:repassword');
		$this->form_validation->set_rules('email', 'lang:email', 'required|xss_clean|callback_email_check');
		$this->form_validation->set_rules('status', 'lang:status', 'required|xss_clean|is_natural');
		$this->form_validation->set_rules('group_id', 'lang:user_group', 'required|xss_clean');

		if ($this->form_validation->run() == TRUE)
		{
			$data = $this->input->post();
			//upload image
			$file = $_FILES;
			$img = $_FILES['avatar'];
			if($img['error'] == 0)
			{
				$this->load->library('upload');

				$add_path = 'avatar';
				$upload_path = FCPATH. DIRECTORY_SEPARATOR .trim($this->config->item('folder_image'), '/');
				$upload_path .= DIRECTORY_SEPARATOR .$add_path;
				$upload_path = path_clean($upload_path);
				folder_create($upload_path);

				$oldimg = path_clean(FCPATH. DIRECTORY_SEPARATOR .trim($this->config->item('folder_image'), '/'). DIRECTORY_SEPARATOR .$item->avatar);
				file_delete($oldimg);

				$ext = $this->upload->get_extension($img['name']);
				$fname = basename($img['name'], $ext);
				$fname = time().'_'.urlTitle($fname).strtolower($ext);
				$config = array(
					'upload_path' => $upload_path,
					'file_name' => $fname,
					'allowed_types' => $this->config->item('allowed_types'),
					'max_size' => $this->config->item('max_filesize'),
					'max_width' => $this->config->item('max_image_width'),
					'max_height' => $this->config->item('max_image_height')
				);
				$this->upload->initialize($config);
				if($this->upload->do_upload('avatar'))
				{
					$img = $this->upload->data();
					$data['avatar'] = $add_path. '/'. $img['file_name'];
				}
				else
				{
					$this->messages->add($upload->display_errors(), 'e');
				}
			}
			if($id)
			{
				if(!$data['password'])
				{
					unset($data['password']);
				}
				$this->messages->add(lang('update_successfully'));
			}
			else
			{
				$this->messages->add(lang('add_successfully'));
			}

			if(isset($data['password']))
			{
				$data['salt'] = $this->user_model->generateSalt();
				$data['password'] = md5($data['salt'].$data['password']);;
			}

			$msg = $this->user_model->save($data);

			redirect(site_url('admin/user/index'));
		}
		else
		{
			$this->messages->add(validation_errors(), 'e');
		}

		$data = array(
			'item'=>$item,
			'usergroup'=>$this->group,
		);

		$this->output->set_template('backend');
		$this->load->view('backend/user/form', $data);
	}
	public function editdetail()
	{
		$this->load->library('form_validation');

		$item = $this->user;
		$this->output->set_title(lang('user_edit_detail'));

		$this->form_validation->set_rules('fullname', 'lang:fullname', 'trim|required|min_length[3]|max_length[64]|xss_clean');

		if ($this->form_validation->run() == TRUE)
		{
			$data = $this->input->post();
			//upload image
			$file = $_FILES;
			$img = $_FILES['avatar'];
			if($img['error'] == 0)
			{
				$this->load->library('upload');

				$add_path = 'avatar';
				$upload_path = FCPATH. DIRECTORY_SEPARATOR .trim($this->config->item('folder_image'), '/');
				$upload_path .= DIRECTORY_SEPARATOR .$add_path;
				$upload_path = path_clean($upload_path);
				folder_create($upload_path);

				$oldimg = path_clean(FCPATH. DIRECTORY_SEPARATOR .trim($this->config->item('folder_image'), '/'). DIRECTORY_SEPARATOR .$item->avatar);
				file_delete($oldimg);

				$ext = $this->upload->get_extension($img['name']);
				$fname = basename($img['name'], $ext);
				$fname = time().'_'.urlTitle($fname).strtolower($ext);
				$config = array(
					'upload_path' => $upload_path,
					'file_name' => $fname,
					'allowed_types' => $this->config->item('allowed_types'),
					'max_size' => $this->config->item('max_filesize'),
					'max_width' => $this->config->item('max_image_width'),
					'max_height' => $this->config->item('max_image_height')
				);
				$this->upload->initialize($config);
				if($this->upload->do_upload('avatar'))
				{
					$img = $this->upload->data();
					$data['avatar'] = $add_path. '/'. $img['file_name'];
				}
				else
				{
					$this->messages->add($upload->display_errors(), 'e');
				}
			}

			if(isset($data['password']))
			{
				$data['salt'] = $this->user_model->generateSalt();
				$data['password'] = md5($data['salt'].$data['password']);;
			}

			$msg = $this->user_model->save($data);
			$this->messages->add(lang('update_successfully'));

			redirect(site_url('admin/user/editdetail'));
		}
		else
		{
			$this->messages->add(validation_errors(), 'e');
		}

		$data = array(
			'item'=>$item,
		);

		$this->output->set_template('backend');
		$this->load->view('backend/user/editdetail', $data);
	}
	public function changepassword()
	{
		$this->load->library('form_validation');

		$item = $this->user;
		$this->output->set_title(lang('user_change_password'));

		$this->form_validation->set_rules('curentpassword', 'lang:curent_password', 'xss_clean|callback_curentpassword_check');
		$this->form_validation->set_rules('password', 'lang:password', 'trim|required|min_length[6]|max_length[64]|xss_clean|matches[repassword]');
		$this->form_validation->set_rules('repassword', 'lang:repassword');

		if ($this->form_validation->run() == TRUE)
		{
			$data = $this->input->post();

			$data['salt'] = $this->user_model->generateSalt();
			$data['password'] = md5($data['salt'].$data['password']);

			$msg = $this->user_model->save($data);
			$this->messages->add(lang('change_password_successfully'));

			redirect(site_url('admin/user/editdetail'));
		}
		else
		{
			$this->messages->add(validation_errors(), 'e');
		}

		$data = array(
			'item'=>$item,
		);

		$this->output->set_template('backend');
		$this->load->view('backend/user/changepassword', $data);
	}
	public function toggle($field='', $id=0, $val=1)
	{
		if($this->user->id!=1 && $id==1)
		{
			$this->messages->add(lang('error_forbidden'), 'e');
			redirect($this->return->get('last'));
		}

		$id = intval($id);
		if(in_array($field, array('published', 'status')))
		{
			$data['id'] = $id;
			$data[$field] = intval($val);
			$this->user_model->update($data);
			$this->messages->add(lang('change_successfully'));
		}
		$ajax = '';
		if($this->input->get('ajax'))
		{
			$ajax = '?ajax=1';
		}
		redirect(site_url('admin/user/index').$ajax);
	}
	public function delete($id=null)
	{
		if($this->user->id!=1 && $id==1)
		{
			$this->messages->add(lang('error_forbidden'), 'e');
			redirect($this->return->get('last'));
		}
		if($this->user->id == $id)
		{
			$this->messages->add(lang('you_cant_delete_youself'), 'e');
			redirect($this->return->get('last'));
		}

		$id = intval($id);
		$this->user_model->delete($id);
		$ajax = '';
		if($this->input->get('ajax'))
		{
			$ajax = '?ajax=1';
		}
		redirect(site_url('admin/user/index').$ajax);
	}

	public function username_check($username)
	{
		if(!preg_match('/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/', $username))
		{
			$this->form_validation->set_message('username_check', lang('invalid_username_character'));
			return false;
		}
		$this->user_model->item_where = array(
			'username'=>$username,
			'id <>'=>intval($this->uri->rsegment(3)),
		);
		$exists = $this->user_model->getUser();
		if($exists)
		{
			$this->form_validation->set_message('username_check', lang('username_exists'));
			return false;
		}
		return true;
	}
	public function curentpassword_check($curentpassword)
	{
		$user = $this->user;
		$exists = $this->user_model->getUser();
		if($user->password <> md5($user->salt.$curentpassword))
		{
			$this->form_validation->set_message('curentpassword_check', lang('error_curentpassword'));
			return false;
		}
		return true;
	}
	public function email_check($email)
	{
		$this->user_model->item_where = array(
			'email'=>$email,
			'id <>'=>intval($this->uri->rsegment(3)),
		);
		$exists = $this->user_model->getUser();
		if($exists)
		{
			$this->form_validation->set_message('email_check', lang('email_exists'));
			return false;
		}
		$this->form_validation->set_message('email_check', lang('valid_email'));
		return $this->form_validation->valid_email($email);
	}
}

